package com.google.code.stalkernet.example.ui.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.nio.charset.Charset;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import com.google.code.stalkernet.database.Database;
import com.google.code.stalkernet.entry.Entry;
import com.google.code.stalkernet.entry.EntryUtils;
import com.google.code.stalkernet.reactor.Reactor;

public class AddEntryAction extends AbstractAction
{
    private final static Charset UTF8 = Charset.forName ("UTF-8");

    private final Reactor reactor;
    private final Database database;

    public AddEntryAction (Reactor reactor, Database database)
    {
        super ("Add Entry");

        if (reactor == null)
            throw new IllegalArgumentException ("Reactor is null");

        if (database == null)
            throw new IllegalArgumentException ("Database is null");

        this.reactor = reactor;
        this.database = database;
    }

    @Override
    public void actionPerformed (ActionEvent e)
    {
        String entryBody = JOptionPane.showInputDialog(
            (Component)e.getSource (), "Entry body:", "Add Entry",
            JOptionPane.PLAIN_MESSAGE);

        if (entryBody != null)
        {
            final Entry entry = database.createEntry (
                EntryUtils.createEntryBody (entryBody.getBytes (UTF8)));

            reactor.invoke (
                new Runnable ()
                {
                    @Override
                    public void run ()
                    {
                        database.addEntry (entry);
                    }
                });
        }
    }
}
